<template>
  <div class="profits view">
    <div class="remind-breadcrumb flexb">
      <div class="flex">
        <div @click="handleToRemind" style="cursor: pointer;">{{ $t('candyBox.vipTool') }}</div>
        <div style="margin: 0 10px;">></div>
        <div>{{$t('ndxStake.positionStatistics')}}</div>
      </div>
    </div>
    <div class="profits-cont table-sty">
      <div class="flexb" style="padding: 0 0 20px 0;">
        <div class="firstStage" :class="{'vipClass': $store.state.app.accountInfo.level > 0}">
          <div v-for="(item, index) in listStatus" :key="index"
          :class="{'active': item.value === checkedValue}"
            @click="handleSelectAction(item.value)">
            {{$t(`order.${item.label}`)}}
          </div>
        </div>
        <el-tooltip placement="bottom" effect="light" popper-class="padd">
          <div slot="content" class="cozyTipContent">
            <p>1. {{$t('ndxStake.profitTip')}}</p>
            <p>2. {{$t('ndxStake.supportProfit')}}</p>
          </div>
          <div class="cozyTip">
            {{$t('ndxStake.stakeDescript')}}
            <i class="iconfont icon-huaban"></i>
          </div>
        </el-tooltip>
      </div>
      <el-table
        :data="tableData"
        v-loading="loading"
        :empty-text="emptyText()"
        :default-sort = "{prop: 'profit', order: 'descending'}">
        <!-- 币种 -->
        <el-table-column
          :label="$t('order.coinCode')"
          width="170">
          <template slot-scope="props">
            <div class="symbolCoinCode">
              <img :src="`https://ndi.340wan.com/${$store.state.app.scatter.chain}/${props.row.symbol0.toLowerCase()}-${props.row.symbol1.toLowerCase()}.png`">
              <span @click="handleToTrad(props.row.symbol)">{{ props.row.symbol1 }} / {{ props.row.symbol2 }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 最新价 -->
        <el-table-column
          :label="$t('jy.newprice')"
          width="170">
          <template slot-scope="props">
            <span>{{ props.row.realTimePrice }} {{props.row.symbol2}}</span>
          </template>
        </el-table-column>
        <!-- 成本价 -->
        <el-table-column
          :label="$t('ndxStake.costPrice')">
          <template slot-scope="props">
            <div v-if="props.row.isSave">
              <span>
                <el-input type="number"
                v-model="costPrice" ref="costPriceInput"
                @blur="handleCostPriceBlur"
                :step="stepFormat(props.row.priceScale)"
                class="inputProfits"
                @mousewheel.native.prevent>
                  <span slot="suffix">{{props.row.symbol2}}</span>
                </el-input>
              </span>
              <span class="blueColor" style="margin-left: 15px;" @click="handleProfitAction(1, props.row)">{{ $t('ndxStake.save') }}</span>
            </div>
            <div v-else :style="Number(props.row.balance) === 0 ? 'padding-right: 47px;' : ''">
              <span>{{props.row.costPrice}} {{props.row.symbol2}}</span>
              <span class="blueColor" style="margin-left: 15px;" v-if="Number(props.row.balance)"
              @click="handleProfitAction(0, props.row)">{{ $t('ndxStake.revise') }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 余额 -->
        <el-table-column
          :label="$t('bosChain.breakEvenPrice')"
          width="250">
          <template slot-scope="props">
            <span>{{ props.row.balance }} {{props.row.symbol1}}</span>
          </template>
        </el-table-column>
        <!-- 盈亏 -->
        <el-table-column
          prop="profit"
          sortable
          :label="$t('ndxStake.profit')"
          width="200">
          <template slot-scope="props">
            <span class="colorGreen" v-if="props.row.profit > 0">
              +{{ props.row.profit }}
            </span>
            <span class="colorRed" v-if="props.row.profit < 0">
              {{ props.row.profit }}
            </span>
            <span v-if="props.row.profit === 0">
              --
            </span>
            <span>{{props.row.symbol2}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { toFixed, toNonExponential, authorized } from '@/utils/validate';

export default {
  name: 'profits', // 盈亏统计
  data() {
    return {
      costPrice: 0,
      loading: false,
      hasDataForTable: 1, // 数据加载中
      tableData: [],
      tableDataAll: [],
      checkedValue: 1, // 选中的估值列表值
      listStatus: [
        {
          value: 0,
          label: 'all',
        },
        {
          value: 1,
          label: 'notSmall2'
        }
      ],
    }
  },
  components: {},
  props: {},
  watch: {
    costPrice: function change(val, oldval) {
      const v = Number(val);
      const o = Number(oldval);
      if (v < 0) {
        this.costPrice = o
      }
      if (v >= 100000000) {
        this.costPrice = o;
      }
    },
  },
  computed: {},
  created() {},
  mounted() {
    // 获取盈亏数据
    this.handleGetProfitInfo()
  },
  beforeDestroy() {},
  methods: {
    // 获取盈亏数据
    handleGetProfitInfo() {
      this.loading = true;
      authorized(this, (code) => { // 授权
        if (code === 'error') {
          this.loading = false;
          return;
        }
        this.$http.get('/exchangeAccountProfit/queryAccountProfits').then((res) => {
          this.loading = false;
          if (res.code !== 0) {
            this.$message.error(res.msg);
            return;
          }
          const list = res.accountProfitVoList;
          this.hasDataForTable = list ? res.accountProfitVoList.length : 0;
          if (list && list.length > 0) {
            list.forEach((vv) => {
              const v = vv;
              const symbolFomat = v.symbol.split('-');
              v.symbol0 = symbolFomat[0].toUpperCase();
              v.symbol1 = symbolFomat[1].toUpperCase();
              v.symbol2 = symbolFomat[2].toUpperCase();
              v.isSave = false;
              v.profit = v.profit === '--' ? 0 : Number(v.profit);
            })
            this.tableDataAll = list;
            this.tableData = list;
            this.handleSelectAction(1);
          }
        })
      });
    },

    // 修正、保存
    handleProfitAction(action, item) {
      const obj = this.tableData.find(v => v.id === item.id);
      const index = this.tableData.findIndex(v => v.id === item.id);
      if (action) { // 保存
        if (Number(this.costPrice) === Number(obj.costPrice)) {
          obj.isSave = false;
          this.$set(this.tableData, index, obj);
          return;
        }
        this.loading = true;
        const params = {
          id: obj.id,
          costPrice: this.costPrice
        }
        this.$http.post('/exchangeAccountProfit/updateCostPrice', params).then((res) => {
          this.loading = false;
          if (res.code !== 0) {
            this.$message.error(res.msg);
            return;
          }
          const cprice = toFixed(this.costPrice, obj.priceScale);
          obj.costPrice = cprice;
          obj.isSave = false;
          this.$set(this.tableData, index, obj);
        })
        return;
      }
      const isSaveTrue = this.tableData.find(v => v.isSave === true);
      if (isSaveTrue) {
        isSaveTrue.isSave = false;
      }
      obj.isSave = true;
      this.$nextTick(() => {
        this.$refs.costPriceInput.focus();
        this.$refs.costPriceInput.select();
      })
      this.costPrice = toNonExponential(Number(obj.costPrice));
      this.$set(this.tableData, index, obj);
    },

    handleCostPriceBlur() {
      const val = Number(this.costPrice);
      if (val < 0) {
        this.costPrice = 0;
      }
      // if (val > 99999999) {
      //   this.costPrice = 99999999;
      // }
      this.costPrice = toNonExponential(Number(this.costPrice))
    },

    // 空数据
    emptyText() {
      const scat = this.$store.state.app.scatter
      if (scat && !scat.identity) {
        return this.$t('jy.sqhlook');
      }
      return this.hasDataForTable ? this.$t('myWallet.loadData') : this.$t('myWallet.noData');
    },

    // 微调数额精度
    stepFormat(p) {
      return 1 / (10 ** p);
    },

    // 科学计数法
    toNonExponential(num) {
      return toNonExponential(num);
    },

    // 回到会员服务首页
    handleToRemind() {
      this.$router.push({
        name: 'services'
      });
    },
    // 跳转到交易页
    handleToTrad(symbol) {
      this.$router.push({
        path: `/trade/${symbol}`
      });
    },
    // 资产切换
    handleSelectAction(val) {
      this.checkedValue = val;
      // balanceEosValuation
      const all = this.tableDataAll;
      if (val === 0) {
        this.tableData = this.tableDataAll;
      }
      if (val === 1) {
        this.tableData = all.filter(v => Number(v.balanceEosValuation) > 0.01 || Math.abs(Number(v.profit)) > 0.1);
      }
      this.hasDataForTable = this.tableData ? this.tableData.length : 0;
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/variables.scss';
$-color: #278EDA;
.blueColor {
  color: #999;
  // color: $-color !important;
  cursor: pointer;

  &:hover {
    color: $-color !important;
  }
}

.color333 {
  color: #333 !important;
}

.colorRed {
  color: #E51C23 !important;
}

.colorGreen {
  color: #259B24;
}

.profits {
  /deep/ .el-input-number__decrease,
  /deep/ .el-input-number__increase {
    display: none!important
  }
  /deep/ .el-input input {
    padding-right: 5px !important;
    text-align: left !important;
  }
}

.firstStage {
  & > div {
    display: inline-block;
    border: 1px solid #D7D7D7;
    padding: 8px 30px;
    cursor: pointer;
    color: #999;
    border-radius: 3px;
    background: #fff;
    margin: 0 25px 0 0;
  }

  .active {
    color: $-btn-skyblue;
    border: 1px solid $-btn-skyblue;
    background: #fff;
  }

  &.vipClass {
    .active {
      color: #E5BC7E;
      border: 1px solid #E5BC7E;
      background: #fff;
    }
  }

  .optional {
    .iconfont {
      display: inline-block;
      vertical-align: middle;
      font-size: 15px !important;
      margin-right: -2px;
    }
  }
}

.cozyTipContent {
  width: 450px;
  font-size: 14px;

  p {
    line-height: 20px;
  }

  p:nth-child(1) {
    margin-bottom: 5px;
  }
}

.cozyTip {
  color: #666;
  cursor: pointer;
}

.view {
  min-height: 600px;

  .remind-breadcrumb {
    padding: 30px 142px 0 40px;
    margin-bottom: 30px;
    color: #333;

    .removeAll {
      color: #278EDA;
      cursor: pointer;
    }
  }

  .profits-cont {
    padding: 0 100px 20px;

    .inputProfits {
      width: 180px;

      /deep/ .el-input__inner {
        padding-left: 5px;
        padding-right: 75px !important;
        width: 180px;
        height: 25px;
        line-height: 25px;;
        -moz-appearance: textfield;
        &::-webkit-outer-spin-button,
        &::-webkit-inner-spin-button {
          -webkit-appearance: none;
        }
      }
    }
  }

  .table-sty /deep/.el-table {
    font-size: 12px;
    .el-table__header-wrapper {
      font-size: 12px;
    }
    .el-table__empty-text {
      font-size: 12px;
      color: #666;
    }
    .cell {
      font-weight: normal;
      line-height: 30px;
      font-size: 14px;
      .symbolCoinCode {
        position: relative;
        cursor: pointer;
        display: block;
        span {
          display: inline-block;
          vertical-align: middle;
          // font-size: 12px !important;

          &:hover {
            // font-weight: bold;
            color: #278EDA;
          }
        }
        img {
          display: inline-block;
          width: 22px;
          height: 22px;
          vertical-align: middle;
          margin-right: 3px;
          background: #fff;
          border-radius: 50%;
        }
        img::after {
          content: '';
          background-image: url('https://ndi.340wan.com/upload/20180919/ed752ac2f6174370bf879620ec821eee.png');
          background-size: cover;
          position: absolute;
          z-index: 2;
          top: 0;
          left: 0;
          width: 22px;
          height: 22px;
          background-color: #fff;
        }
      }
    }
    .cell span{
      font-size: 14px;
    }

    .el-table__expand-icon {
      visibility: hidden;
    }

    .el-table__body tr .cell,
    .el-table__header tr .cell{
      text-align: right;
    }

    .el-table__body tr td:nth-child(1) .cell,
    .el-table__header tr th:nth-child(1) .cell {
      text-align: left;
      padding: 6px 0 6px 18px;
      line-height: 16px;
    }

    .el-table__header tr th:nth-child(3) .cell {
      padding-right: 55px;
    }

    .el-table__header tr .cell{
      color: #999;
    }
  }
}

.theme-1B1D27 {
  .cozyTip {
    color: rgba(255,255,255, 0.6);
  }
  .firstStage {
    & > div {
      background: $-topcolor;
      border-color: #4e5b85;
      color: #7b8db9;
    }
    .active {
      color: $-btn-skyblue;
      background: $-topcolor;
    }

    &.vipClass {
      .active {
        color: #E5BC7E;
      }
    }
  }

  .remind-breadcrumb {
    color: rgba(255, 255, 255, 0.6);
  }

  .blueColor {
    color: rgba(255, 255, 255, 0.6);
  }

  .table-sty /deep/.el-table {
    .el-table__empty-text {
      color: rgba(255, 255, 255, 0.6);
    }

    .cell {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
</style>
